package com.common.www.service.auth;

import org.springframework.boot.base.jpa.service.BaseService;
import com.common.www.bean.entity.auth.AuthUser;
import com.common.www.bean.entity.auth.Token;
import com.common.www.data.global.RabbitEnum;
import com.common.www.repository.auth.TokenRepository;
import com.common.www.utils.JwtUtils;
import com.common.www.utils.TimeUtils;
import com.common.www.utils.TxtUtil;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by cwx183898 on 2017/12/14.
 */
@Service
@Transactional
public class TokenService extends BaseService<Token, Long> {
    @Autowired
    private TokenRepository repository;
    @Autowired
    UserService userService;
    @Autowired
    RabbitTemplate rabbitTemplate;  //使用RabbitTemplate,这提供了接收/发送等等方法

    @Override
    public TokenRepository getRepository() {
        return repository;
    }

    /**
     * 根据token查找用户
     */
    public AuthUser findUserByToken(String token) {
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        List<Token> list = queryToList(map, null);
        if (list != null && list.size() > 0) {
            Token t = list.get(0);
            Map<String, Object> hashMap = new HashMap<>();
            hashMap.put("id", t.getUser());
            List<AuthUser> authUserList = userService.queryToList(hashMap, null);
            if (authUserList != null && authUserList.size() > 0) {
                AuthUser authUser = authUserList.get(0);
                return authUser;
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    public Token findToken(String token) {
        HashMap hashMap = new HashMap();
        hashMap.put("token", token);
        List<Token> list = queryToList(hashMap, null);

        Token res = null;
        if (list.size() > 0) {
            res = list.get(0);
        }

        return res;
    }

    public Token findTokenByUser(String userId) {
        HashMap hashMap = new HashMap();
        hashMap.put("user", userId);
        List<Token> list = queryToList(hashMap, null);

        Token res = null;
        if (list.size() > 0) {
            res = list.get(0);
        }

        return res;
    }

    /**
     * 是否是可用token
     */
    public boolean isAvailableToken(String token) {
        boolean flag = false;
        if (TxtUtil.isEmpty(token)) {
            return flag;
        }

        List<HashMap> list = getRepository().executeSqlQuery(
                "select last_update_timetamp from auth_token where token=?", new String[]{token}, HashMap.class
        );

        if (list == null || list.size() == 0) {
            return false;
        }
        Long storyTime = TxtUtil.getLong(list.get(0).get("last_update_timetamp") + "");
        Long now = TimeUtils.getLocalDatestamp();
        if (now - storyTime > JwtUtils.TOKEN_EXP_MS) {//超时
            flag = false;
        } else {
//            res.setLastUpdateTimetamp(TimeUtils.getLocalDatetamp());
//            res.setLastUpdateTime(TimeUtils.getLocalDate());
//            save(res);//保存最新请求时间
            //放到映射表中，定时更新刷新时间
//            JwtUtils.lastUpdateHastmap.put(token, TimeUtils.getLocalDatetamp());
            //发送事务(事务为异步)
            HashMap hashMap = new HashMap();
            hashMap.put("token", token);
            hashMap.put("datetamp", TimeUtils.getLocalDatestamp());
            hashMap.put("date", TimeUtils.getLocalDate());
            rabbitTemplate.convertAndSend(RabbitEnum.TOKEN.getExchange(), RabbitEnum.TOKEN.getRouting(), hashMap);
            flag = true;
        }
        return flag;
    }

    /**
     * 正常使用时授权token
     *
     * @return token
     */
    public Token authToken(String userID, String tokenStr) {
        Map<String, Object> map = new HashMap<>();
        map.put("user", userID);
        List<Token> list = queryToList(map, null);

        Token token = new Token();
        if (list != null && list.size() > 0) {
            token = list.get(0);
        } else {//token不存在时才重新绑定token
            token.setUser(userID);
        }
        token.setToken(tokenStr);
        token.setLastUpdateTime(new Date());
        token.setLastUpdateTimetamp(TimeUtils.getLocalDatestamp());

        token = save(token);
        flush();
        return token;
    }

}
